package com.colter.project.sample.thread.part04.test1;

import java.util.Date;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

//周期性执行任务 
public class Test5 {
	public static void main(String[] args) {
		ScheduledThreadPoolExecutor executor = (ScheduledThreadPoolExecutor) Executors.newScheduledThreadPool(1);
		//executor.setContinueExistingPeriodicTasksAfterShutdownPolicy(true); //设置 executor shutdown后，周期任务执行完毕。
		Task5 task = new Task5("task");
		ScheduledFuture<?> result = executor.scheduleAtFixedRate(task, 1, 1, TimeUnit.SECONDS);
		
		for (int i = 0; i < 10; i++) {
			System.out.println("Main: Delay:"+result.getDelay(TimeUnit.MILLISECONDS));
			try {
				Thread.sleep(500);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		
		executor.shutdown();
		
		try {
			Thread.sleep(5000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		System.out.println("Main: finish at "+new Date());
	}
}

class Task5 implements Runnable {
	private String name;

	public Task5(String name) {
		super();
		this.name = name;
	}

	@Override
	public void run() {
		System.out.println(name + " start at:" + new Date());
	}
}